"""
logger.py - logger utility, originally written for AsciiBlast

Copyright 2009 Roberto Nerici <roberton [at] bloggo.org>
"""

import time

class Logger:
    """
    Simple utility class to help with logging. Logging is to a file with
    each line timestamped relative to the time the object was initialised.
    Public API is simple:
        - log(string) to log something
        - on/off to enable/disable
    """

    def __init__(self):
        """Create log file and set time used as a base for timestamps."""
        self._is_on = False
        self._start_time = time.time()
        self._file = open("log.log", "w")

    def _timediff_as_string(self, start_time, end_time):
        """
        Static function that returns difference between two times as string
        formatted in the style seconds:milliseconds.
        """
        timediff = end_time - start_time
        assert(timediff >= 0)
        secs_string = str(int(timediff))
        ms_string = str(int(1000 * (timediff - int(timediff))))
        return secs_string + ":" + ms_string

    def log(self, string):
        """Log the 'string', prepending with a relative timestamp."""
        if self._is_on:
            dt_string = self._timediff_as_string(self._start_time,  time.time())
            print >> self._file, dt_string, string

    def on(self):
        """Enable logging."""
        self._is_on = True

    def off(self):
        """Disable logging, calls to log() will do nothing in this state."""
        self._is_on = False


